package it.blueocean.acanto.taglibrary.jsp.taglib.tags.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ClobReader
{
	private static final String MS_SQL_SERVER = "Microsoft";

	private static final String POSTGRESQL = "PostgreSQL";

	private static final String ORACLE = "Oracle";

	private static final String MYSQL = "MySQL";

	private static final int READ_BUFFER_SIZE = 16384;

	ResultSet rs = null;

	String databaseName = null;

	public ClobReader(String paramString, ResultSet paramResultSet) throws SQLException
	{
		this.rs = paramResultSet;
		this.databaseName = paramString;
	}

	public ClobReader(Connection paramConnection, ResultSet paramResultSet) throws SQLException
	{
		this.rs = paramResultSet;
		this.databaseName = getDBMS(paramConnection);
	}

	public String getText(int paramInt) throws SQLException
	{
		String str = null;
		if((this.databaseName.indexOf("Microsoft") != -1) || (this.databaseName.indexOf("PostgreSQL") != -1)
				|| (this.databaseName.indexOf("MySQL") != -1))
		{
			str = this.rs.getString(paramInt);
		}
		else if(this.databaseName.indexOf("Oracle") != -1)
		{
			Clob localClob = this.rs.getClob(paramInt);
			str = getTextFromClob(localClob);
		}
		return str;
	}

	public String getText(String paramString) throws SQLException
	{
		String str = null;
		if((this.databaseName.indexOf("Microsoft") != -1) || (this.databaseName.indexOf("PostgreSQL") != -1)
				|| (this.databaseName.indexOf("MySQL") != -1))
		{
			str = this.rs.getString(paramString);
		}
		else if(this.databaseName.indexOf("Oracle") != -1)
		{
			Clob localClob = this.rs.getClob(paramString);
			str = getTextFromClob(localClob);
		}
		return str;
	}

	public boolean next() throws SQLException
	{
		return this.rs.next();
	}

	public void close() throws SQLException
	{
		this.rs.close();
	}

	private String getDBMS(Connection paramConnection) throws SQLException
	{
		String str = paramConnection.getMetaData().getDatabaseProductName();
		return str;
	}

	private String getTextFromClob(Clob paramClob) throws SQLException
	{
		StringBuffer localStringBuffer = new StringBuffer();
		try
		{
			char[] arrayOfChar = new char[16384];
			int i = 0;
			BufferedReader localBufferedReader = new BufferedReader(paramClob.getCharacterStream());
			while ((i = localBufferedReader.read(arrayOfChar, 0, 16384)) != -1)
				localStringBuffer.append(arrayOfChar, 0, i);
			localBufferedReader.close();
		}
		catch (IOException localIOException)
		{
			localIOException.printStackTrace();
			throw new SQLException();
		}
		return localStringBuffer.toString();
	}
}
